package com.lxy.cxcyxmmsbackend.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxy.cxcyxmmsbackend.sys.entity.QxglUser;
import com.lxy.cxcyxmmsbackend.sys.entity.XmkjDsjl;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.res.Result;
import com.lxy.cxcyxmmsbackend.sys.service.CxcyXmService;
import com.lxy.cxcyxmmsbackend.sys.service.QxglUserService;
import com.lxy.cxcyxmmsbackend.sys.service.XmfjDsjlService;
import com.lxy.cxcyxmmsbackend.sys.utils.UUIDUtil;
import com.lxy.cxcyxmmsbackend.sys.utils.UpPhotoNameUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房间打扫记录
 *
 * @author 刘新颖
 * @since 2024-01-07
 */
@Api(tags = "房间打扫记录")
@RestController
@RequestMapping("/xmfjDsjl")
public class XmfjDsjlController {

    @Autowired
    XmfjDsjlService xmfjDsjlService;

    @Resource
    CxcyXmService cxcyXmService;

    @Resource
    QxglUserService qxglUserService;

    @Autowired
    Environment environment;

    @ApiOperation("查询项目空间打扫记录")
    @PostMapping("/queryXmfjDsjl")
    public Result queryXmfjDsjl(@RequestBody PageReq pageReq) {
        Integer pageNo = pageReq.getCurrentPage();
        Integer pageSize = pageReq.getPageSize();
        Page<XmkjDsjl> pages = new Page<>(pageReq.getCurrentPage(), pageReq.getPageSize());
        QueryWrapper<XmkjDsjl> wrapper = new QueryWrapper<>();
        String kjhm = pageReq.getKeyWord().get("kjhm");
        String xmBh = pageReq.getKeyWord().get("xmBh");
        String jcsj = pageReq.getKeyWord().get("jcsj");
        String sfhg = pageReq.getKeyWord().get("sfhg");

        //房间号
        if (kjhm != null && !"".equals(kjhm)) {
            wrapper.lambda().eq(XmkjDsjl::getXmfjHm, kjhm);
        }

        //项目名称
        if (xmBh != null && !"".equals(xmBh)) {
            wrapper.lambda().like(XmkjDsjl::getXmBh, xmBh);
        }

        if (sfhg != null && !"".equals(sfhg)) {
            wrapper.lambda().like(XmkjDsjl::getStatus, sfhg);
        }
        //检查时间
        if (jcsj != null && !"".equals(jcsj)) {
            String format = LocalDateTime.parse(jcsj, DateTimeFormatter.ISO_DATE_TIME).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            wrapper.lambda().eq(XmkjDsjl::getXmfjDsjlJcsj, format);
        }

        wrapper.orderByDesc("XMFJ_DSJL_JCSJ");

        IPage<XmkjDsjl> page = xmfjDsjlService.page(pages, wrapper);

        HashMap<Object, Object> map = new HashMap<>();

        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        List<XmkjDsjl> records = page.getRecords();

        map.put("rows", records);
        map.put("total", page.getTotal());
        map.put("pageNums", (int) Math.ceil((double) page.getTotal() / pageSize));

        return Result.success("查询项目空间打扫记录成功", map);
    }


    @ApiOperation("新增项目空间打扫记录")
    @PostMapping("/addXmfjDsjl")
    @Transactional
    public Result addXmfjDsjl(@RequestBody XmkjDsjl xmkjDsjl, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);
        if ("".equals(xmkjDsjl.getXmfjDsjlBh()) || xmkjDsjl.getXmfjDsjlBh() == null) {
            xmkjDsjl.setXmfjDsjlBh(UUIDUtil.getUUID8("D", 8));
            xmkjDsjl.setXmfjDsjlTjrbh(userBh);
            xmkjDsjl.setXmfjDsjlTjrmc(user.getUserMc());
            xmkjDsjl.setXmfjDsjlZp("img.png");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            xmkjDsjl.setXmfjDsjlJcsj(format.format(new Date(System.currentTimeMillis())));
            xmkjDsjl.setStatus("0");
            boolean save = xmfjDsjlService.save(xmkjDsjl);
            if (!save) {
                throw new NormalException("新增项目空间打扫记录失败");
            }
        } else {
            boolean save = xmfjDsjlService.updateById(xmkjDsjl);
            if (!save) {
                throw new NormalException("修改项目空间打扫记录失败");
            }
        }

        return Result.success("保存项目空间打扫记录成功", null);
    }

    @ApiOperation("审批项目空间打扫记录")
    @PostMapping("/approvalXmfjDsjl")
    @Transactional
    public Result approvalXmfjDsjl(@RequestBody XmkjDsjl xmkjDsjl, HttpServletRequest request) {
        String userBh = request.getHeader("userBh");
        QxglUser user = qxglUserService.getById(userBh);

        xmkjDsjl.setXmfjDsjlSprbh(userBh);
        xmkjDsjl.setXmfjDsjlSprmc(user.getUserMc());
        boolean save = xmfjDsjlService.updateById(xmkjDsjl);
        if (!save) {
            throw new NormalException("审批记录失败");
        }
        return Result.success("审批打扫记录成功", xmkjDsjl);
    }

    @ApiOperation("删除项目空间打扫记录")
    @PostMapping("/removeXmfjDsjl/{bh}")
    @Transactional
    public Result removeXmfjDsjl(@PathVariable("bh") String bh) {
        boolean remove = xmfjDsjlService.removeById(bh);
        if (!remove) {
            throw new NormalException("删除项目空间打扫记录失败");
        }
        return Result.success("删除项目空间打扫记录成功", null);
    }

    @ApiOperation("提交项目空间打扫记录")
    @PostMapping("/tijiaoXmfjDsjl/{xmfjDsjlBh}")
    @Transactional
    public Result tijiaoXmfjDsjl(@PathVariable("xmfjDsjlBh") String xmfjDsjlBh) {
        XmkjDsjl byId = xmfjDsjlService.getById(xmfjDsjlBh);
        if (byId.getXmfjDsjlZp().equals("img.png")){
            throw new NormalException("请先上传图片！");
        }
        byId.setStatus("1");
        boolean save = xmfjDsjlService.updateById(byId);
        if (!save) {
            throw new NormalException("提交项目空间打扫记录失败");
        }
        return Result.success("提交项目空间打扫记录成功", null);
    }

    @ApiOperation("获取项目空间打扫记录详情")
    @PostMapping("/getXmfjDsjlDetail/{xmfjDsjlBh}")
    @Transactional
    public Result getXmfjDsjlDetail(@PathVariable("xmfjDsjlBh") String xmfjDsjlBh) {
        XmkjDsjl byId = xmfjDsjlService.getById(xmfjDsjlBh);
        if (byId == null) {
            throw new NormalException("获取项目空间打扫记录详情失败");
        }
        return Result.success("获取项目空间打扫记录详情成功", byId);
    }


    @ApiOperation("上传项目房间打扫")
    @RequestMapping("uploadDSFJ")
    public String uploadTX(@RequestParam("file") MultipartFile file, HttpServletRequest request, String upxmfjDsjlBh) {
        QueryWrapper<XmkjDsjl> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(XmkjDsjl::getXmfjDsjlBh, upxmfjDsjlBh);
        XmkjDsjl xmkjDsjl = xmfjDsjlService.getOne(wrapper);

        try {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
            String url = environment.getProperty("front-assert-url.dsjl");
            Path path = Paths.get(url + fileName);
            Files.write(path, bytes);//写入文件
            String avatar_url = fileName;
            xmkjDsjl.setXmfjDsjlZp(avatar_url);
            boolean b = xmfjDsjlService.updateById(xmkjDsjl);

            System.out.println(fileName + "\n");
            return fileName;//返回文件名字
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }



}

